import axios from 'axios';
import { HashRouter } from 'react-router-dom';
import qs from 'qs';

// 创建axios实例
const service = axios.create({
  timeout: 1000 * 30,
  // 允许跨域带token
  withCredentials: true,
  // headers: {
  //   'Content-Type': 'application/json; charset=utf-8',
  // },
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers.token = sessionStorage.getItem('token') ? sessionStorage.getItem('token') : '';
    config.data = qs.stringify(config.data);
    // if (config.params) {
    //   config.params.reagent_type = sessionStorage.getItem('reagent_type') ? sessionStorage.getItem('reagent_type') : '';
    // }
    // console.log(config.headers.token);
    // if(config.url.indexOf("http://result.eolinker.com")) {
    //   config.headers['token'] = Vue.cookie.get('token') ? Vue.cookie.get('token') : '74c8ffe4a59da108f03aa7afc77cc24e';
    // }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  });

// response拦截器
service.interceptors.response.use((response) => {
  if (response.data && response.data.code === 401) { // 401, token失效
    sessionStorage.clear();
    const router = new HashRouter();
    router.history.push('/user');
    // this.props.history.push('/user/login');
  }
  return response;
}, (error) => {
  return Promise.reject(error);
});




export default service;
